<?php 
namespace app\index\controller;
use app\index\model\News as NewModel;
use think\Session;
use think\Loader;
use think\db;

class News extends ComContro{
	//后台左侧文章列表导航list
	public function list(){
	$del = "";
		if(Session::has('del')){
			$del = Session::get('del');
			Session::delete('del');
		}
		$news = new NewModel();
		$arr = $news->limit(10)->select();
		// print_r($arr);
		return view('',['arr'=>$arr,'del'=>$del]);
	}
	//新闻列表编辑页面
	public function edit($id){
		//编辑新闻时 验证标题和内容不合规则时显示错误提示
		$error="";
		if(Session::has('error')){
			$error = Session::get('error');
			Session::delete('error');
		}
		$news = NewModel::get($id);
		return view('',['news'=>$news,'msg'=>$error]);
	}
	//编辑页面的数据处理
	public function editCheck($id){
		$news = new NewModel;
		$title = input('post.title');
		$content  = input('post.content');
		//标题和内容都不为空时去验证是否合法
		if(!empty($title) && !empty($content)){
			$data = [
				'title' => $title,
				'content'=> $content
			];
			$validate = Loader::validate('AddVerify');
			//如果验证失败 重定向到edit页面 带id
			if(!$validate->check($data)){
				$error = $validate->getError();
				session::set('error',$error);
				$this->redirect('/index/news/edit/id/'.$id);
			}else{
				//验证通过，通过获取ID值 更新数据
				$editRes = $news->update([
					'id' => $id,
					'title'  => $title,
					'content' => $content
				]);
				if($editRes){
					$this->success("更新成功！");
				}else{
					$this->error("更新失败！！");
				}
			}
		}else{
			//标题和内容为空时 重定向到edit
			$this->redirect('/index/news/edit/id/'.$id);
		}
	}
	//添加新闻
	public function add(){
		$error="";
		if(Session::has('error')){
			$error = Session::get('error');
			Session::delete('error');
		}
			return view('',['msg'=>$error]);
	}
	//添加新闻数据处理
	public function addCon(){
		$news = new NewModel;
		$title = input('post.title');
		$content  = input('post.content');

		if(!empty($title) && !empty($content)){
			$data = [
				'title' => $title,
				'content'=> $content
			];
			$validate = Loader::validate('AddVerify');
			if(!$validate->check($data)){
				$error = $validate->getError();
				session::set('error',$error);
				$this->redirect('/index/news/add');
			}else{
				$news->title = $title;
				$news->content = $content;
				$addRes = $news->save();
				if($addRes){
					$this->success("添加成功！");
				}else{
					$this->error("添加失败！！");
				}
			}
		}else{
			$this->redirect('/index/news/add');
		}
	}
	//删除新闻 获取id删除
	public function delete($id){
		//获取删除文章的id 删除成功后返回列表页 并提示删除成功 删除失败同理
		$news = NewModel::get($id);
		$delRes = $news->delete();
		//删除成功
		if($delRes){
 			session::set('del',"删除成功");
			$this->redirect('/index/news/list');
		}else{
			session::set('del',"删除失败");
			$this->redirect('/index/news/list');
		}	
	}
	
}

